﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SvnNotes
{
    public class SvnNotesFile
    {
        public static void Create(Stream svnXmlLogStream, string outputFileName, params string[] args)
        {
            Create(svnXmlLogStream, outputFileName, new DefaultOutputTransformer());
        }

        public static void Create(Stream svnXmlLogStream, string outputFileName, IOutputTransformer outputTransformer, params string[] args)
        {
            if (outputTransformer == null) outputTransformer = new DefaultOutputTransformer();
            if (String.IsNullOrEmpty(outputFileName)) throw new ArgumentException("cannot be null or empty", "outputFileName");
            if (svnXmlLogStream == null) throw new ArgumentNullException("svnXmlLogStream");

            Dictionary<string, EntryCollection> entries;

            SvnNotesParser parser = new SvnNotesParser(svnXmlLogStream);

            entries = parser.Parse();

            outputTransformer.Entries = entries;

            object output = outputTransformer.Transform();
            if (output == null) throw new InvalidProgramException(String.Format("{0}.Transform() returned null", outputTransformer.GetType().Name));

            if (output is string)
            {
                File.WriteAllText(outputFileName, output.ToString());
            }
            else if (output is byte[])
            {
                File.WriteAllBytes(outputFileName, (byte[])output);
            }
            else
            {
                throw new InvalidProgramException(String.Format("{0}.Transform() must return a string or an array of bytes", outputTransformer.GetType().Name));
            }
        }
    }
}
